<template>
    <div class="confirm-order">
        <div class="steps">
            <el-steps :space="300" :active="active" finish-status="success">
                <el-step title="拍下商品"></el-step>
                <el-step title="支付"></el-step>
                <el-step title="确认收货"></el-step>
            </el-steps>
        </div>
        <div class="choose-address">
            <h1>选择收货地址</h1>
            <div class="card">
                <AddressCard ref="address" v-for="(item, index) in addressArr" :key="item.id" :addressItem="item"
                    :index="index" :currentIndex="currentIndex" @changeIndex="changeIndex(index)"
                    @getDefaultAddress="getDefaultAddress">
                </AddressCard>
            </div>
            <div class="bottom">
                <el-button type="default" size="small" @click="newAddress">使用新地址</el-button>
                <span @click="goAddress">管理收货地址</span>
            </div>
        </div>
        <div class="confirm">
            <h2>确认订单信息</h2>

            <div v-if="$route.query.num === 'nums'">
                <OrderInfo v-for="item in checked" :key="item.id" :checkedObj="item" @moreGoods="moreGoods"></OrderInfo>
            </div>

            <div class="order-info" v-else>
                <OrderInfo :checkedObj="goodsState" :num="productQty" @chuangProductQty="chuangProductQty"></OrderInfo>
            </div>

        </div>
        <div class="pay">
            <span>实付款：
                <span>￥</span>
                <i v-if="$route.query.num === 'nums'">{{ totalPrice }}</i>
                <i v-else>{{ price }}</i>

            </span>
            <el-button type="danger" @click="submitOrder" v-if="isPay == 0">提交订单</el-button>
            <el-button type="text" v-else @click="goOrderDetail">支付成功，可前往 我的订单 页面查看 订单详情</el-button>
        </div>
        <el-dialog title="" :visible.sync="dialogVisible" width="15%" :showClose="false">
            <el-result icon="success" title="支付成功" subTitle="请根据提示进行操作"></el-result>
            <!-- <el-result icon="error" title="支付失败" subTitle="账户余额不足，请充值"></el-result> -->
        </el-dialog>
        <AddAddress></AddAddress>
    </div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
import AddressCard from './address_card/index.vue'
import OrderInfo from './order_info/index'
import AddAddress from '../../components/add_address/index.vue'
export default {
    name: 'ConfirmOrder',
    components: {
        AddressCard,
        OrderInfo,
        AddAddress
    },
    mixins: [],
    props: {

    },
    data() {
        return {
            active: JSON.parse(localStorage.getItem('active')) || 1,
            productQty: this.$route.query.num,
            dialogVisible: false,
            id: this.$route.query.id,
            currentIndex: -1,
            chooseAddress: {},//选中的地址
            isPay: JSON.parse(localStorage.getItem('isPay')) || 0
        }
    },
    computed: {
        ...mapState('goodsStore', ['goodsState']),
        ...mapState('userStore', ['userInfo']),
        ...mapState('cartStore', ['cart']),
        ...mapState('addressStore', ['addressArr']),
        price() {
            return (this.goodsState?.price * this.productQty).toFixed(2)
        },
        checked() {
            return this.cart.filter(item => item.checked === true)
        },
        totalPrice() {
            return this.checked.reduce((amount, item) => amount += item.productQty *
                item.price, 0).toFixed(2)
        },

    },
    watch: {

    },
    mounted() {
        this.getGoodsData(this.id)
        this.getAddressList()
    },
    methods: {
        ...mapMutations('goodsStore', ['getGoodsData']),
        ...mapMutations('addressStore', ['getAddressList']),
        ...mapMutations('cartStore', ['editCartGoods']),
        ...mapMutations('userStore', ['updateUserInfo', 'getUserInfo']),
        goAddress() {
            this.$router.push('/address')
        },
        // 接收要新增的地址的信息
        update(InfoObj) {

        },
        newAddress() {
            const obj = {
                title: '新增收货地址',
                true: true
            }
            this.$bus.$emit('add', obj)
        },
        // 下单多个商品
        moreGoods(goodsObj) {
            this.editCartGoods(goodsObj)
        },
        submitOrder() {
            // 判断 是否已选有收货地址
            if (this.currentIndex === -1) {
                this.$message({
                    type: 'warning',
                    message: "请选择收货地址！"
                })

            } else {
                // 判断下单的商品是一个还是多个
                if (this.$route.query.num === 'nums') {
                    const productOrderVOS = this.checked.map(item => ({ productId: item.productId, productQty: item.productQty }))
                    const obj = {
                        addressId: this.chooseAddress.id,
                        productOrderVOS: productOrderVOS
                    }
                    this.$confirm('确认付款?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.request.post('/order/orderAdd', obj).then(res => {
                            if (res.code == 20000) {
                                // const obj = {
                                //     balance: this.totalPrice
                                // }
                                // this.updateUserInfo(obj)
                                this.getUserInfo()
                                this.$message({
                                    type: 'success',
                                    message: '支付成功!'
                                });

                                this.isPay = 1
                                localStorage.setItem('isPay', JSON.stringify(this.isPay))
                                this.active = 2
                                localStorage.setItem('active', JSON.stringify(this.active))
                                this.$router.push('/orders')
                            } else {
                                this.$message({
                                    type: 'warning',
                                    message: res.msg
                                })
                            }
                        })
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消支付！'
                        });
                    });
                } else {
                    // 立即购买
                    const obj = {
                        addressId: this.chooseAddress.id,
                        productOrderVOS: [
                            {
                                productId: this.goodsState.id,
                                productQty: this.productQty
                            }
                        ]
                    }
                    this.$confirm('确认付款?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.request.post('/order/orderAdd', obj).then(res => {
                            if (res.code == 20000) {
                                this.getUserInfo()
                                this.$message({
                                    type: 'success',
                                    message: '支付成功!'
                                });
                                this.isPay = 1
                                localStorage.setItem('isPay', JSON.stringify(this.isPay))
                                this.active = 2
                                localStorage.setItem('active', JSON.stringify(this.active))
                                this.$router.push('/orders')
                            } else {
                                this.$message({
                                    type: 'warning',
                                    message: res.msg
                                })
                            }
                        })
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消支付！'
                        });
                    });
                }
            }
        },
        changeIndex(index) {
            this.currentIndex = index
            // 拿到选中的地址信息
            this.chooseAddress = this.$refs.address[index].addressItem

        },
        getDefaultAddress() {
            // 默认地址
            const defaultAddress = this.$refs.address.find(item => item.addressItem.isDefault === 1)
            this.currentIndex = defaultAddress.index
            // 获取默认的地址信息
            this.chooseAddress = defaultAddress.addressItem
        },
        chuangProductQty(productQty) {
            this.productQty = productQty
        },
        goOrderDetail() {
            this.$router.push('/orders')
        }
    }
};
</script>
<style lang='less' scoped>
.confirm-order {
    width: 70%;
    margin: 10px auto;

    .el-result {
        padding: 30px 0;
    }


    .steps {
        width: 900px;
        margin: 0 auto;
    }

    .choose-address {
        margin: 40px 0;

        h1 {
            margin: 10px 0;
            font-weight: bold;
            color: #333;
        }

        .card {
            width: 100%;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
        }

        .bottom {
            margin-top: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            span {
                color: #c97;
                font-size: 13px;
                cursor: pointer;

            }

            span:hover {
                text-decoration: underline;
            }
        }
    }

    .confirm {
        h2 {
            font-weight: bold;
            margin: 20px 0
        }

        .order-info {
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            color: #7f7f7f;

            img {
                width: 60px;
                height: 60px;
                margin-right: 10px;
            }

            .title {
                width: 300px;
                overflow: hidden;
                text-overflow: ellipsis;
                text-wrap: nowrap;
            }

            .price {
                width: 300px;

                span {
                    font-weight: bold;
                }
            }

            .count {
                width: 300px;
            }

            .total {
                width: 300px;

                span {
                    color: red;
                    font-weight: bold;
                }
            }
        }
    }

    .pay {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-top: 1px solid #c0c0c0;
        margin-top: 20px;
        border-bottom: 1px solid #c0c0c0;
        padding: 20px 0;

        span {

            span {
                font-size: 18px;
                color: red;

            }

            i {
                font-size: 30px;
                font-weight: bold;
                color: red;

            }
        }
    }
}
</style>